package com.jsbj.tools;


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * Created by lenovo12 on 2018/8/18.
 */
public final class FileUtil {
    private FileUtil() {
    }

    /**
     * 获取后缀
     *
     * @param fileName 文件名
     * @return 后缀名
     */
    public static String getFileSuffix(String fileName) {
        if (StringUtils.isEmpty(fileName) || fileName.lastIndexOf(".") < 0) {
            return "error";
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static void downloadExcel(String name, HttpServletResponse response, XSSFWorkbook workbook) {
        BufferedOutputStream fos = null;
        try {
            String fileName = name + ".xls";
            response.setContentType("application/x-msdownload");
            response.addHeader("Access-Control-Expose-Headers", "File-Name");
            response.addHeader("File-Name", URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
            fos = new BufferedOutputStream(response.getOutputStream());
            workbook.write(fos);
        } catch (Exception e) {
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static void downloadExcelHSS(String name, HttpServletResponse response, HSSFWorkbook workbook) {
        BufferedOutputStream fos = null;
        try {
            String fileName = name + ".xls";
            response.setContentType("application/x-msdownload");
            response.addHeader("Access-Control-Expose-Headers", "File-Name");
            response.addHeader("File-Name", URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
            fos = new BufferedOutputStream(response.getOutputStream());
            workbook.write(fos);
        } catch (Exception e) {
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static void downloadExcelSXSS(String name, HttpServletResponse response, SXSSFWorkbook workbook) {
        BufferedOutputStream fos = null;
        try {
            String fileName = name + ".xlsx";
            response.setContentType("application/x-msdownload");
            response.addHeader("Access-Control-Expose-Headers", "File-Name");
            response.addHeader("File-Name", URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
            fos = new BufferedOutputStream(response.getOutputStream());
            workbook.write(fos);
        } catch (Exception e) {
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static void downloadFileByPath(String path, String filename, HttpServletResponse response) {
        File file = new File(path);
        if (filename == null || "".equals(filename)) {
            filename = file.getName();
        }
        try {
            // 以流的形式下载文件
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            // 设置response的Header
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(filename, "UTF-8"));
            response.addHeader("Content-Length", "" + file.length());
            response.addHeader("Access-Control-Expose-Headers", "File-Name");
            response.addHeader("File-Name", URLEncoder.encode(filename, "UTF-8"));
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * easypoi 的文件导出
     *
     * @param workbook
     * @param folderName
     * @param fileName
     */
    public static File easypoiFileDownload(Workbook workbook, HttpServletResponse response, String folderName, String fileName) throws IOException {
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            file = checkOrCreateFile(folderName, fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            workbook.write(fileOutputStream);
            fin = new FileInputStream(file);
            response.setContentType("application/json;charset=UTF-8");
//            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1")+".xls");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xls");
            response.setHeader("filename", URLEncoder.encode(fileName, "UTF-8") + ".xls");
            response.setHeader("Access-Control-Expose-Headers", "filename");
            out = response.getOutputStream();
            byte[] buffer = new byte[512]; // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fin != null) {
                fin.close();
                fin = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
        }
        return file;
    }

    /**
     * 判断路径下是否有文件如果不存在则创建
     *
     * @param folderName
     * @param fileName
     */
    public static File checkOrCreateFile(String folderName, String fileName) throws IOException {
        File dir = new File(folderName);
        dir.setWritable(true, false);
        File file2 = new File(dir.getPath() + "/" + fileName);
        if (!dir.exists()) {
            dir.mkdirs();
            file2.createNewFile();
        } else {
            if (file2.exists()) {
                file2.delete();
                file2.createNewFile();
            } else {
                file2.createNewFile();
            }
        }
        return file2;
    }

}
